# coding:utf-8
from sqlalchemy import Column, String, Integer, DateTime, Text

from database import dbconnect, session_maker, model_list, model_dict

_, _, DBase = dbconnect()


class Alerts(DBase):
    __tablename__ = 'alerts'
    __table_args__ = {'extend_existing': True}
    id = Column(Integer, primary_key=True)
    status = Column(String(50))
    labels = Column(Text)
    alertname = Column(String(255))
    instance = Column(String(255))
    severity = Column(String(255))
    annotations = Column(Text)
    content = Column(String(255)) # 取annotations中的message或description
    startsAt = Column(DateTime)
    endsAt = Column(DateTime)
    fingerprint = Column(String(255))
    person = Column(String(255))
    solution = Column(Text)
    closed = Column(Integer)
    type = Column(String(255))
    updateAt = Column(DateTime)
    handleAt = Column(DateTime)
    closeAt = Column(DateTime)
    source = Column(String(255))

    def find_by_fingerprint(self, fingerprint):
        with session_maker() as session:
            row = session.query(Alerts).filter_by(fingerprint=fingerprint).first()
            return model_dict(row)

    # 查询所有告警
    def find_all(self):
        with session_maker() as session:
            result = session.query(Alerts).all()
            list = model_list(result)
            return list

    # 查询所有特定状态的告警   "resolved": "已解决", "firing": "告警中"
    def find_all_by_status(self, status):
        with session_maker() as session:
            result = session.query(Alerts).filter_by(status=status).all()
            list = model_list(result)
            return list

    # 统计总数
    def get_total_count(self):
        with session_maker() as session:
            count = session.query(Alerts).count()
            return count

    # 统计特定状态的告警数量
    def get_status_count(self, status):
        with session_maker() as session:
            count = session.query(Alerts).filter_by(status=status).count()
            return count


class AlertSource(DBase):
    __tablename__ = 'alert_source'
    id = Column(Integer, primary_key=True)
    name = Column(String(255))
    token = Column(String(255))  # 根据name使用md5生成
    critical_dd_token = Column(String(255))
    spec_dd_token = Column(String(255))
    # 添加告警自检字段
    prom_heartbeat_check = Column(Integer)
    prom_heartbeat_time = Column(DateTime)


class AlertsSwk(DBase):
    __tablename__ = 'alerts_skw'
    id = Column(Integer, primary_key=True)
    scope = Column(String(255))
    name = Column(String(255))
    ruleName = Column(String(255))
    alarmMessage = Column(Text)
    startTime = Column(DateTime)
    source = Column(String(255))

    # 查询所有告警
    def find_all(self):
        with session_maker() as session:
            result = session.query(AlertsSwk).all()
            list = model_list(result)
            return list